<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>post | GS0401</title><meta name="author" content="John Doe"><meta name="copyright" content="John Doe"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="前言 函数重载是 C++ 编程的一个特性，它允许我们有多个具有相同名称但不同参数列表的函数，当我说参数列表时，它表示参数的数据类型和顺序，例如函数myfuncn(int a, float b)的参数列表是(int, float)，它与函数myfuncn(float a, int b)参数列表(float, int)不同。函数重载是编译时多态。 重载规则 现在我们知道什么是参数列表，让我们看一下重载">
<meta property="og:type" content="article">
<meta property="og:title" content="post">
<meta property="og:url" content="http://example.com/2022/05/29/ss/%E5%87%BD%E6%95%B0%E9%87%8D%E8%BD%BD/index.html">
<meta property="og:site_name" content="GS0401">
<meta property="og:description" content="前言 函数重载是 C++ 编程的一个特性，它允许我们有多个具有相同名称但不同参数列表的函数，当我说参数列表时，它表示参数的数据类型和顺序，例如函数myfuncn(int a, float b)的参数列表是(int, float)，它与函数myfuncn(float a, int b)参数列表(float, int)不同。函数重载是编译时多态。 重载规则 现在我们知道什么是参数列表，让我们看一下重载">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="">
<meta property="article:published_time" content="2022-05-29T03:44:45.000Z">
<meta property="article:modified_time" content="2022-05-29T03:44:57.749Z">
<meta property="article:author" content="John Doe">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content=""><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2022/05/29/ss/%E5%87%BD%E6%95%B0%E9%87%8D%E8%BD%BD/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'post',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2022-05-29 11:44:57'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.2.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">27</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr/></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">GS0401</a></span><div id="menus"><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">post</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-05-29T03:44:45.000Z" title="发表于 2022-05-29 11:44:45">2022-05-29</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-05-29T03:44:57.749Z" title="更新于 2022-05-29 11:44:57">2022-05-29</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="post"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>前言</p>
<p>函数重载是 C++ 编程的一个特性，它允许我们有多个具有相同名称但不同参数列表的函数，当我说参数列表时，它表示参数的数据类型和顺序，例如函数myfuncn(int a, float b)的参数列表是(int, float)，它与函数myfuncn(float a, int b)参数列表(float, int)不同。函数重载是编译时多态。</p>
<p>重载规则</p>
<p>现在我们知道什么是参数列表，让我们看一下重载规则：我们可以在同一范围内拥有以下函数。</p>
<p>print(int num1, int num2)<br>print(int num1, int num2, int num3)<br>print(int num1, double num2)<br>1<br>2<br>3<br>记住这条规则的最简单方法是参数应符合以下任何一个或多个条件，它们应具有不同的类型，数量或顺序的参数。</p>
<p>例如：</p>
<p>这两个函数有不同的参数类型：</p>
<p>print(int num1, int num2)<br>print(double num1, double num2)<br>1<br>2<br>这两个的参数数量不同：</p>
<p>print(int num1, int num2)<br>print(int num1, int num2, int num3)<br>1<br>2<br>这两个有不同的参数顺序：</p>
<p>print(int num1, double num2)<br>print(double num1, int num2)<br>1<br>2<br>以上三种情况都是有效的重载情况。我们可以有任意数量的函数，只需记住参数列表应该是不同的。例如：</p>
<p>int print(int, int)<br>double print(int, int)<br>1<br>2<br>由于参数列表相同，因此不允许这样做。尽管它们具有不同的返回类型，但它无效。</p>
<p>函数重载例1</p>
<p>函数重载指的是一个作用域内的几个函数名字相同但是形参列表不同。</p>
<p>#include <iostream><br>#include <string><br>using namespace std;</p>
<p>class Test<br>{<br>public:<br>    void print(int i)<br>    {<br>        cout &lt;&lt;”int: “&lt;&lt;i&lt;&lt;endl;<br>    }</p>
<pre><code>void print(double f)
&#123;
    cout &lt;&lt;&quot;float: &quot;&lt;&lt;f&lt;&lt;endl;
&#125;

void print(string s)
&#123;
    cout &lt;&lt;&quot;string: &quot;&lt;&lt;s&lt;&lt;endl;
&#125;
</code></pre>
<p>};</p>
<p>int main(int argc, char const *argv[])<br>{</p>
<pre><code>Test test;
test.print(50);
test.print(89.5);
test.print(&quot;minger&quot;);

return 0;
</code></pre>
<p>}</p>
<p>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>25<br>26<br>27<br>28<br>29<br>30<br>31<br>32<br>33<br>34<br>35<br>编译结果:</p>
<p>函数重载例2</p>
<p>正如我在本指南开头所提到的，具有不同返回类型和相同参数列表的函数不能重载。但是，如果函数具有不同的参数列表，则它们可以具有相同或不同的返回类型，以便有资格进行重载。简而言之，函数的返回类型在函数重载中不起任何作用。重要的是函数的参数列表。</p>
<p>#include <iostream><br>using namespace std;</p>
<p>class DemoClass {</p>
<p>public:<br>    int print(int i) {<br>        return i;<br>    }<br>    double print(double d) {<br>        return d;<br>    }</p>
<p>};</p>
<p>int main(int argc, char const *argv[]) {</p>
<pre><code>DemoClass obj;
cout&lt;&lt;obj.print(100)&lt;&lt;endl;
cout&lt;&lt;obj.print(5005.516)&lt;&lt;endl;
</code></pre>
<p>   return 0;<br>}<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>编译输出：</p>
<p>C++的重载函数与转换构造函数</p>
<p>当我们调用重载的函数时，从多个数类型转换中进行选择将变得更复杂。如果两个或者多个类型转换都提供了同一种可行匹配，则这些类型转换一样好。<br>举个例子，当几个重载函数的参数分属不同的类类型时，如果这些类恰好定义了同样的转换构造函数，则二义性问题将进一步提升：</p>
<p>#include <iostream><br>using namespace std;</p>
<p>struct TEST1<br>{<br>    int a;<br>    int b;</p>
<p>};</p>
<p>struct TEST2<br>{<br>    int c;<br>};</p>
<p>void print(const TEST1&amp;)<br>{<br>    cout &lt;&lt;”TEST1”&lt;&lt;endl;<br>}</p>
<p>void print(const TEST2&amp;)<br>{<br>    cout &lt;&lt;”TEST2”&lt;&lt;endl;<br>}</p>
<p>int main(int argc, char const *argv[])<br>{<br>    TEST1 test1;<br>    TEST1 test2;</p>
<pre><code>print(test1);
return 0;
</code></pre>
<p>}<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>25<br>26<br>27<br>28<br>29<br>30<br>31<br>32<br>33</p>
<p>如果在调用重载函数时候，我们需要使用构造函数或者强制类型转换来改变实参类型。避免二义性发生。</p>
<p>C++ 有哪些函数不能重载</p>
<p>析构函数不能重载 ，因为析构函数只能有一个，且不能带参数。析构函数是系统自动调用的，是没有参数表的 。</p>
<p>main函数不能重载</p>
<p>这是在C++ 11标准中说明的：</p>
<p>A program shall contain a global function called main, which is the designated start of the program….<br>This function shall not be overloaded.<br>1<br>2<br>试想如果作为用户程序入口函数的main函数被重载了，那么加载的时候该以哪个为入口呢？</p>
<p>重载函数返回值不同、形参名不同都是不能重载的</p>
<p>double print(const A&amp;);<br>int print(const A&amp;);<br>1<br>2<br>编译会出错，仅有返回值不同是不可以重载的</p>
<p>int print(const A&amp;test1);<br>int print(const A&amp;test2);<br>1<br>2<br>编译会出错，仅仅是形参名不同，不可以重载。同名函数的形式参数（指参数的个数、类型或者顺序）必须不同。</p>
<p>总结</p>
<p>函数重载是在同一个作用域内，可以声明几个功能类似的同名函数，但是这些同名函数的形式参数（指参数的个数、类型或者顺序）必须不同。不能仅通过返回类型的不同来重载函数。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">John Doe</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2022/05/29/ss/%E5%87%BD%E6%95%B0%E9%87%8D%E8%BD%BD/">http://example.com/2022/05/29/ss/%E5%87%BD%E6%95%B0%E9%87%8D%E8%BD%BD/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">GS0401</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/gh/overtrue/share.js@master/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/05/29/%E5%85%B3%E4%BA%8Enode.js/"><img class="prev-cover" src="" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">push</div></div></a></div><div class="next-post pull-right"><a href="/2022/05/27/hello-world/"><img class="next-cover" src="" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Hello World</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">John Doe</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">27</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/06/21/nginx%E7%9A%84%E5%9F%BA%E7%A1%80%E5%85%A5%E9%97%A8/" title="nginx的基础入门"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="nginx的基础入门"/></a><div class="content"><a class="title" href="/2022/06/21/nginx%E7%9A%84%E5%9F%BA%E7%A1%80%E5%85%A5%E9%97%A8/" title="nginx的基础入门">nginx的基础入门</a><time datetime="2022-06-20T23:49:26.000Z" title="发表于 2022-06-21 07:49:26">2022-06-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/06/21/vue3/" title="vue3"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="vue3"/></a><div class="content"><a class="title" href="/2022/06/21/vue3/" title="vue3">vue3</a><time datetime="2022-06-20T23:48:21.000Z" title="发表于 2022-06-21 07:48:21">2022-06-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/06/21/%E4%BD%BF%E7%94%A8%E5%88%86%E6%94%AF%E5%BC%80%E5%8F%91%E5%8A%9F%E8%83%BD%EF%BC%8C%E5%90%88%E5%B9%B6/" title="使用分支开发功能，合并"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="使用分支开发功能，合并"/></a><div class="content"><a class="title" href="/2022/06/21/%E4%BD%BF%E7%94%A8%E5%88%86%E6%94%AF%E5%BC%80%E5%8F%91%E5%8A%9F%E8%83%BD%EF%BC%8C%E5%90%88%E5%B9%B6/" title="使用分支开发功能，合并">使用分支开发功能，合并</a><time datetime="2022-06-20T23:47:54.000Z" title="发表于 2022-06-21 07:47:54">2022-06-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/06/21/git%E7%9A%84%E9%AB%98%E7%BA%A7%E6%93%8D%E4%BD%9C/" title="git的高级操作"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="git的高级操作"/></a><div class="content"><a class="title" href="/2022/06/21/git%E7%9A%84%E9%AB%98%E7%BA%A7%E6%93%8D%E4%BD%9C/" title="git的高级操作">git的高级操作</a><time datetime="2022-06-20T23:46:37.000Z" title="发表于 2022-06-21 07:46:37">2022-06-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/06/20/p10%E6%80%BB%E7%BB%93/" title="p10总结"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="p10总结"/></a><div class="content"><a class="title" href="/2022/06/20/p10%E6%80%BB%E7%BB%93/" title="p10总结">p10总结</a><time datetime="2022-06-20T08:54:35.000Z" title="发表于 2022-06-20 16:54:35">2022-06-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By John Doe</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>